// src/utils/useAMap.ts
let AMapLoaderPromise: Promise<any> | null = null

export function loadAMap(key: string): Promise<any> {
    if (!AMapLoaderPromise) {
        AMapLoaderPromise = new Promise((resolve, reject) => {
            if (typeof window.AMap !== "undefined") {
                resolve(window.AMap)
                return
            }

            const script = document.createElement("script")
            script.type = "text/javascript"
            script.src = `https://webapi.amap.com/maps?v=2.0&key=${key}`
            script.onload = () => {
                // 脚本加载后可能需要一些时间来初始化 AMap 对象
                const checkAMap = (retries = 10) => {
                    if (window.AMap) {
                        resolve(window.AMap)
                    } else if (retries > 0) {
                        setTimeout(() => checkAMap(retries - 1), 100)
                    } else {
                        reject(new Error('AMap 脚本加载后未找到 AMap 对象'))
                    }
                }
                checkAMap()
            }
            script.onerror = (err) => {
                reject(new Error('AMap 脚本加载失败: ' + err))
            }
            document.head.appendChild(script)
        })
    }
    return AMapLoaderPromise
}
